package ro.peoplecentric.ctc.faces.util.ui;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import ro.peoplecentric.ctc.common.entity.Item;
import ro.peoplecentric.ctc.common.exception.ApplicationException;
import ro.peoplecentric.ctc.common.service.ItemService;

/**
 * {@link Item} converter.
 *
 * @author pguzun
 */
@Component
public class ItemConverter implements Converter {

    @Resource
    private ItemService itemService;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (!StringUtils.isEmpty(value) && value.matches("\\d+")) {
            try {
                Item item = itemService.getById(Long.valueOf(value));
                if (item != null) {
                    return item;
                }
            } catch (ApplicationException ex) {
                Logger.getLogger(ItemConverter.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        throw new ConverterException(new FacesMessage("Unknown item ID: " + value));

    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (!(value instanceof Item) || ((Item) value).getId() == null) {
            return null;
        }
        return String.valueOf(((Item) value).getId());
    }
}
